import os
import cv2
from function.readTxtFile import readBBox_XYWH, readPoints

class Landmark_label17(object):
    '''
    landmark 17点顺序：
                6              10
            5       7       9       11
                8       0      12

                        1
                    2   3   4

                        15
                13              14
                        16
    '''
    def __init__(self, imagePath, box, lm):
        self.imagePath = imagePath
        self.used = True

        if len(box) == 4:
            self.bbox = box
        else:
            self.bbox = []
            self.used = False
        if len(lm) == 17:
            self.lm = lm
        else:
            self.lm = []
            self.used = False

def getMirrorLM(lm, img_w):
    '''
    得到镜像landmark,镜像landmark顺序为[0,1,4,3,2,11,10,9,12,7,6,5,8,14,15,13,16]
    :return:
    '''
    if len(lm) != 17:
        return []
    mirr_order = [0, 1, 4, 3, 2, 11, 10, 9, 12, 7, 6, 5, 8, 14, 15, 13, 16]
    lm[:, 0] = img_w - lm[:, 0]
    lm = lm[mirr_order]
    return lm

def getMirrorBox(box, img_w):
    box[0] = img_w - box[0]
    return box

class Reader(object):
    '''
    各种深度学习标签阅读的基类，为了统一训练
    '''
    def __init__(self):
        self.flag = None

    def readLabel(self, imagePath):
        pass

class Reader_LM17(Reader):
    def __init__(self, bboxSuffix, labelSuffix):
        self.flag = "lm17"
        self.bboxsuffix = bboxSuffix
        self.labelSuffix = labelSuffix

    def readLabel(self, imagePath):
        if not os.path.exists(imagePath):
            return Landmark_label17(imagePath, [], [])
        boxfile = os.path.splitext(imagePath)[0] + "." + self.bboxsuffix
        labelfile = os.path.splitext(imagePath)[0] + "." + self.labelSuffix
        box = self.readBox(boxfile)
        lm = self.readLandmark(labelfile)

        return Landmark_label17(imagePath, box, lm)

    def readBox(self, boxPath):
        bbox = readBBox_XYWH(boxPath)
        if bbox.bbox is not None:
            bbox = bbox.bbox
        else:
            bbox = []
        return bbox

    def readLandmark(self, lmPath):
        lm = readPoints(lmPath, 2)
        if len(lm) != 17:
            lm = []
        return lm




